//
//  MasterViewController.m
//  Budget
//
//  Created by Barak on 10/26/12.
//  Copyright (c) 2012 Barak. All rights reserved.
//

#import "LimitationRulesController.h"

#import "DetailViewController.h"
#import "PQHttpRequest.h"

@interface LimitationRulesController () {
    double _totalBudget;
}

@end

@implementation LimitationRulesController



- (void)awakeFromNib
{
    [super awakeFromNib];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [self.tableView registerClass:[SubjectCellView class] forCellReuseIdentifier:@"SubjectCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SubjectCellView" bundle:nil] forCellReuseIdentifier:@"SubjectCell"];

    
	// Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

//    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
//    self.navigationItem.rightBarButtonItem = addButton;
    
//    _subjects = [[NSMutableArray alloc] init];
//    [_subjects addObjectsFromArray:@[@"Food", @"Clothing", @"Vecatation", @"Electronics", @"Others"]];
    


}

- (void) setBudgetrules:(NSArray *)budgetrules {
    _budgetrules = budgetrules;
    
    for (BudgetRule* rule in _budgetrules) {
        if ([rule.category isEqualToString:@"Total budget"]) {
            
            _totalBudget = [rule.budgetLimit doubleValue];
            break;
        }
    }
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)insertNewObject:(id)sender
//{
//    if (!_subjects) {
//        _subjects = [[NSMutableArray alloc] init];
//    }
//    [_subjects insertObject:[NSDate date] atIndex:0];
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//}


#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.editing ? 70 : 110;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _budgetrules.count;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{

        return UITableViewCellEditingStyleNone;

}
- (void)setEditing:(BOOL)flag animated:(BOOL)animated
{
    

    if (!flag){

        for (BudgetRule* rule in _budgetrules) {

             NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/budgets/%@?limit=%@", OUR_SERVER_URL, rule.budgetId, rule.budgetLimit]];

            [PQHttpRequest getJSONFromURL:url response:^(id response, NSError *error) {
                
            }];
        }
        
        

    }
    self.tableView.rowHeight = self.editing ? 70 : 110;
    
    [self.tableView reloadData];
    [super setEditing:flag animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     
    SubjectCellView *cell = [tableView dequeueReusableCellWithIdentifier:@"SubjectCell" forIndexPath:indexPath];

    if (cell == nil){
        cell = [self createLimitCellForSubject];
    }
    
    cell.shouldIndentWhileEditing = NO;
    cell.editing = self.editing;
    
    cell.totalBudget = _totalBudget;
    cell.rule = _budgetrules[indexPath.row];
    [cell updateProgress];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.

    } else {

    }
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (SubjectCellView*) createLimitCellForSubject {
    SubjectCellView* cell;
    NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SubjectCellView" owner:nil options:nil];
    for (id currObject in topLevelObjects) {
        if ([currObject isKindOfClass:[UITableViewCell class]]) {
            cell = (SubjectCellView*)currObject;
            break;
        }
    }
    
    return cell;
}



@end
